import 'package:flutter/material.dart';

class TrackReport with WidgetsBindingObserver {
  TrackReport._() {
    WidgetsBinding.instance.addObserver(this);
  }
  static TrackReport? _instance;
  static TrackReport get instance => _getOrCreateInstance();
  static TrackReport _getOrCreateInstance() {
    if (_instance != null) {
      return _instance!;
    } else {
      _instance = TrackReport._();
      return _instance!;
    }
  }

  // 等待上报埋点
  List<Map<String, dynamic>> waitReportMapList = [];
  // 网络请求中埋点
  List<Map<String, dynamic>> reportingMapList = [];

  static _track(Map<String, dynamic> params) {
    TrackReport.instance.appendTrackData(params);
    // if (BaseCoreSp.enableTrackLog.value) {
    //   LoggerUtil.dt('YouthTrackReport', json.encode(params));
    // }
  }

  appendTrackData(Map<String, dynamic> params) {
    TrackReport.instance.waitReportMapList.add(params);
    beginReportIfNeeded();
  }

  beginReportIfNeeded() {
    if (TrackReport.instance.waitReportMapList.length >= 10) {
      TrackReport.instance.reportingMapList =
          List.from(TrackReport.instance.waitReportMapList);
      requestNetwork(TrackReport.instance.reportingMapList);
      TrackReport.instance.waitReportMapList = [];
    }
  }

  requestNetwork(List<Map<String, dynamic>> listMap) {
    // TDApiService.post('/v1/metric/miniapp')
    //     .tag('')
    //     .needFilterRequest(false)
    //     .params({
    //   'v': json.encode(paramsFinal.trimNull()),
    //   'share_uid': '',
    //   'sid': '',
    // }).request;
    bool success = true;
    if (!success) {
      TrackReport.instance.waitReportMapList
          .addAll(TrackReport.instance.reportingMapList);
    }
    TrackReport.instance.reportingMapList = [];
  }

  ///监听应用生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      //从后台切换前台，界面可见
    } else if (state == AppLifecycleState.inactive) {
    } else if (state == AppLifecycleState.paused) {
      beginReportIfNeeded();
    } else if (state == AppLifecycleState.detached) {}
  }

  /// [eventName] 英文
  /// [event] 中文
  static trackEvent(String eventName, String event, [Map? params]) {
    _track({'eventName': eventName, 'event': event, ...?params});
  }

  /// [windowName] 英文
  /// [windowTitle] 中文
  static trackPopWindow(
    String windowName,
    String windowTitle, {
    dynamic windowId,
    dynamic windowType,
    dynamic sourceType,
    Map? extraParams,
  }) {
    _track({
      'eventName': 'pop_window',
      'event': '弹窗',
      'window_name': windowName,
      'window_title': windowTitle,
      'window_id': windowId,
      'window_type': windowType,
      'source_type': sourceType,
      ...?extraParams,
    });
  }

  /// [windowName] 英文
  /// [windowTitle] 中文
  static trackElementShow(
    String pageName,
    String elementName,
    String elementTitle, {
    dynamic elementStatus,
    dynamic sourceType,
  }) {
    _track({
      'eventName': 'elementShow',
      'event': '元素曝光',
      'page_name': pageName,
      'element_name': elementName,
      'element_title': elementTitle,
      if (elementStatus != null) 'element_status': elementStatus,
      if (sourceType != null) 'source_type': sourceType,
    });
  }

  /// [windowName] 英文
  /// [windowTitle] 中文
  static trackElementClick(
    String pageName,
    String elementName,
    String elementTitle, {
    dynamic elementStatus,
    dynamic sourceType,
  }) {
    _track({
      'eventName': 'elementClick',
      'event': '元素点击',
      'page_name': pageName,
      'element_name': elementName,
      'element_title': elementTitle,
      if (elementStatus != null) 'element_status': elementStatus,
      if (sourceType != null) 'source_type': sourceType,
    });
  }
}
